<template>
	<div class="main" v-loading="loading">
		<div class="content">
			<div class="title">医院名称</div>
			<div class="search">
				<el-input v-model="areaObj.name" style="width: 240px" clearable placeholder="请输入区域" />
				<el-input v-model="hospitalObj.name" clearable style="width: 240px; margin-left: 10px" placeholder="请输入医院" />
				<el-button type="primary" style="margin-left: 10px" @click="handleSearchHospitals">搜索</el-button>
				<el-button type="" style="margin-left: 10px" @click="handleReset">重置</el-button>
			</div>
			<el-scrollbar view-class="list">
				<el-tree style="width: 600px" node-key="id" ref="treeRef" :default-checked-keys="checkedKeys" :props="props" :data="hospitalList" :load="loadNode" lazy show-checkbox @check-change="handleProductCheckChange">
					<template #default="scope">
						<el-icon style="margin-right: 6px; color: #ffd659; font-size: 16px">
							<svg v-if="!scope.data?.leaf" data-v-730513b0="" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="4" stroke-linejoin="round" style="fill: currentcolor"><path d="M3 6H16L25 14H45V42H3Z"></path></svg>
							<svg v-else data-v-730513b0="" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linejoin="round" style="transform: scale(0.9) translateY(1px); color: #faad14">
								<path d="M28 2V16H41M28 2H7V45H41V16Z"></path>
								<path d="M15 14H22"></path>
								<path d="M15 25H33"></path>
								<path d="M15 35H33"></path>
							</svg>
						</el-icon>
						<span class="el-tree-node__label" style="margin-top: 2px">
							{{ scope.data.title }}
						</span>
					</template>
				</el-tree>
			</el-scrollbar>
		</div>
		<div class="footer">
			<el-button class="btn" type="" @click="router.go(-1)">取消</el-button>
			<el-button class="btn" type="primary" @click="save">保存</el-button>
		</div>
	</div>
</template>
<script setup>
	import { ref, onMounted, nextTick, onUnmounted } from 'vue';
	import { getHospitalAreaList, getHospitalList, addHabitHospital, getHabitHospital } from '@/api/HabitBandHospital/index';
	import { useRoute, useRouter } from 'vue-router';
	import { ElMessage } from 'element-plus';
	const route = useRoute();
	const router = useRouter();

	//树的实例
	const treeRef = ref(null);

	//loading 加载
	const loading = ref(false);

	//搜索区域对象
	const areaObj = ref({
		id: '',
		name: ''
	});

	//搜索医院对象
	const hospitalObj = ref({
		id: '',
		name: ''
	});

	//已选的节点
	const checkedKeys = ref([]);

	//医院数据
	const hospitalList = ref([]);

	//搜索医院
	const handleSearchHospitals = async () => {
		//先把树形控件数据保存一下
		let hospitalSelected = treeRef.value.getCheckedKeys(true);
		checkedKeys.value = [...checkedKeys.value, ...hospitalSelected];
		//去重
		checkedKeys.value = [...new Set(checkedKeys.value)];

		// 如果有区域 有医院 就搜索医院
		if (areaObj.value.name && hospitalObj.value.name) {
			getHospitalData();
		} else if (areaObj.value.name && !hospitalObj.value.name) {
			getAreasData();
		} else if (!areaObj.value.name && hospitalObj.value.name) {
			getHospitalData();
		} else {
			ElMessage.warning('请输入搜索条件');
		}
	};

	//获取区域
	const getAreasData = async () => {
		const res = await getHospitalAreaList({ key: areaObj.value.name });
		console.log(res);
		if (!res.data.length) {
			hospitalList.value = [];
		}
		hospitalList.value = res.data.map((item) => {
			return {
				...item,
				leaf: false
			};
		});
	};

	//获取医院
	const getHospitalData = async () => {
		const res = await getHospitalList({ order_type: 1, company_area_id: areaObj.value.id, key: hospitalObj.value.name });
		if (!res.data.length) {
			hospitalList.value = [];
		}
		hospitalList.value = res.data.map((item) => {
			return {
				...item,
				leaf: true
			};
		});

		//清空上一次保存的区域id
		areaObj.value.id = '';
	};

	//重置
	const handleReset = async () => {
		//先把树形控件数据保存一下
		let hospitalSelected = treeRef.value.getCheckedKeys(true);
		checkedKeys.value = [...checkedKeys.value, ...hospitalSelected];
		//去重
		checkedKeys.value = [...new Set(checkedKeys.value)];
		console.log(checkedKeys.value);

		areaObj.value = {
			id: '',
			name: ''
		};
		hospitalObj.value = {
			id: '',
			name: ''
		};
		//获取区域
		getAreasData();
	};

	////匹配节点是否在已选节点中
	const handleProductCheckChange = (data, checked, indeterminate) => {
		nextTick(() => {
			if (checkedKeys.value.includes(data.id)) {
				//如果已选节点中存在该节点，则删除该节点
				checkedKeys.value = checkedKeys.value.filter((item) => item !== data.id);
			}
		});
	};

	//获取已关联的节点 回显
	const getHabitHospitalList = async () => {
		let res = await getHabitHospital({ product_habit_id: route.query.habit_id });
		checkedKeys.value = res.data;
	};

	//保存
	const save = async () => {
		//获取选中的节点
		let checkedNodes = treeRef.value.getCheckedKeys(true);

		//拼接
		checkedNodes = [...checkedKeys.value, ...checkedNodes];

		//去重
		checkedNodes = [...new Set(checkedNodes)];

		console.log(checkedNodes);

		if (!checkedNodes.length) {
			ElMessage.error('请选择医院');
			return;
		}

		try {
			loading.value = true;

			let res = await addHabitHospital({
				product_habit_id: route.query.habit_id,
				hospital_id: checkedNodes.join(',')
			});
			console.log(res);
			ElMessage.success(res.msg);
			loading.value = false;
		} catch (err) {
			ElMessage.error(err.msg);
			loading.value = false;
		}
	};

	//配置项
	const props = {
		label: 'title',
		isLeaf: 'leaf'
	};

	//懒加载
	const loadNode = async (node, resolve) => {
		if (node.level === 0) {
			loading.value = true;
			let res = await getHospitalAreaList();
			console.log(res);
			if (res.data.length) {
				loading.value = false;
				return resolve(
					res.data.map((item) => {
						return {
							...item,
							leaf: false
						};
					})
				);
			} else {
				loading.value = false;
				return resolve([]);
			}
		}
		if (node.level !== 0) {
			loading.value = true;
			//点击节点时保存区域id 搜索时用
			areaObj.value.id = node.key;
			let res = await getHospitalList({ order_type: 1, company_area_id: node.key });
			console.log(res);
			if (res.data.length) {
				loading.value = false;
				return resolve(
					res.data.map((item) => {
						return {
							...item,
							leaf: true
						};
					})
				);
			} else {
				loading.value = false;
				return resolve([]);
			}
		}
	};

	onMounted(() => {
		if (route.query.habit_id) {
			//获取回显
			getHabitHospitalList();
		}
	});

	//页面卸载
	onUnmounted(() => {
		areaObj.value = {
			id: '',
			name: ''
		};
		hospitalObj.value = {
			id: '',
			name: ''
		};
	});
</script>
<style lang="scss" scoped>
	.main {
		box-sizing: border-box;
		width: 100%;
		height: 100vh;
		background-color: #fff;

		.content {
			box-sizing: border-box;
			height: calc(100vh - 70px);
			overflow: auto;
			width: 100%;
			padding: 10px;
			display: flex;
			flex-direction: column;
			align-items: center;
			.title {
				font-size: 18px;
				font-weight: 700;
			}
		}

		.footer {
			box-sizing: border-box;
			width: 100%;
			height: 40px;
			margin-bottom: 30px;
			display: flex;
			align-items: center;
			justify-content: center;

			.btn {
				width: 150px;
				height: 40px;
			}
		}
	}
</style>
